package com.zhiyinlou.api.util.http;

import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.alibaba.fastjson.JSONObject;

import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;

public class HttpclientUtil {
	private static CloseableHttpClient httpClient;
	private static CloseableHttpResponse response = null;

	public static Logger logger = LogManager.getLogger(HttpclientUtil.class);

	static {
		PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
		cm.setMaxTotal(200);
		cm.setDefaultMaxPerRoute(20);
		cm.setDefaultMaxPerRoute(50);
		httpClient = HttpClients.custom().setConnectionManager(cm).build();
	}

	/**
	 * 普通get请求
	 * 
	 * @param url
	 * @param requestHeaders
	 * @return
	 */
	public static String httpCommonGet(String url, HashMap<String, String> requestHeaders) {

		HttpGet httpGet = new HttpGet();

		try {
			httpGet.setURI(new URI(url));

			for (Entry<String, String> entry : requestHeaders.entrySet()) {
				httpGet.setHeader(entry.getKey(), entry.getValue());
			}
			response = httpClient.execute(httpGet);

			// 如果server端返回http 200
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				HttpEntity responseEntity = response.getEntity();
				return EntityUtils.toString(responseEntity, "UTF-8");
			} else {
				String code = String.valueOf(response.getStatusLine().getStatusCode());
				return "请求失败:" + code;
			}
		} catch (Exception e) {
			return "不可能出现";
		}

	}

	/**
	 * 普通post请求
	 * 
	 * @param url
	 * @param requestHeaders
	 * @param requestParams
	 * @return
	 */
	public static String httpCommonPost(String url, HashMap<String, String> requestHeaders,
			HashMap<String, String> requestParams) {
		HttpPost httpPost = new HttpPost(url);
		List<NameValuePair> params = new ArrayList<NameValuePair>();

		for (Entry<String, String> entry : requestHeaders.entrySet()) {
			httpPost.setHeader(entry.getKey(), entry.getValue());
		}
		if (null != requestParams) {
			// 对request中的value转换
			Iterator<Entry<String, String>> requestIte = requestParams.entrySet().iterator();

			while (requestIte.hasNext()) {
				Map.Entry<String, String> requestEntry = requestIte.next();
				requestEntry.setValue(requestEntry.getValue());
			}

			Set<String> keys = requestParams.keySet();

			for (String key : keys) {
				params.add(new BasicNameValuePair(key, requestParams.get(key)));
			}
		}

		try {
			if (null != requestParams) {
				UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, "utf-8");
				httpPost.setEntity(entity);
			}
			response = httpClient.execute(httpPost);
			// 如果server端返回http 200
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				HttpEntity responseEntity = response.getEntity();
				return EntityUtils.toString(responseEntity, "UTF-8");
			} else {
				String code = String.valueOf(response.getStatusLine().getStatusCode());
				logger.error("请求返回code：" + code);
				return "请求失败:" + code;

			}
		} catch (Exception e) {
			logger.error("不可能出现");
			return "不可能出现";
		}
	}

	/**
	 * post json数据
	 * 
	 * @param url
	 * @param requsetHeaders
	 * @param jsonObj
	 * @return
	 */
	public static String httpJsonPost(String url, HashMap<String, String> requsetHeaders, JSONObject jsonObj) {
		HttpPost httpPost = new HttpPost(url);

		for (Entry<String, String> entry : requsetHeaders.entrySet()) {
			httpPost.setHeader(entry.getKey(), entry.getValue());
		}

		try {
			StringEntity strEntity = new StringEntity(jsonObj.toString(), "UTF-8");
			strEntity.setContentType("application/json");
			httpPost.setEntity(strEntity);
			response = httpClient.execute(httpPost);

			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				HttpEntity responseEntity = response.getEntity();
				return EntityUtils.toString(responseEntity, "UTF-8");
			} else {
				String code = String.valueOf(response.getStatusLine().getStatusCode());
				HttpEntity responseEntity = response.getEntity();
				System.out.println(EntityUtils.toString(responseEntity, "UTF-8"));
				return "请求失败:" + code;
			}
		} catch (Exception e) {
			return "不可能出现";
		}
	}

	/**
	 * 发送 http put 请求，参数以原生字符串进行提交
	 * 
	 * @param url
	 * @param requsetHeaders
	 * @param jsonObj
	 * @return
	 */
	public static String httpJsonPut(String url, Map<String, String> requsetHeaders, JSONObject jsonObj) {

		HttpPut httpput = new HttpPut(url);

		// 设置header
		for (Entry<String, String> entry : requsetHeaders.entrySet()) {
			httpput.setHeader(entry.getKey(), entry.getValue());
		}

		try {
			// 组织请求参数
			StringEntity stringEntity = new StringEntity(jsonObj.toString(), "utf-8");
			stringEntity.setContentEncoding("UTF-8");
			stringEntity.setContentType("application/json");
			httpput.setEntity(stringEntity);

			response = httpClient.execute(httpput);

			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				HttpEntity responseEntity = response.getEntity();
				return EntityUtils.toString(responseEntity, "UTF-8");
			} else {
				String code = String.valueOf(response.getStatusLine().getStatusCode());
				return "请求失败:" + code;
			}
		} catch (Exception e) {
			return "不可能出现";
		}
	}

	/**
	 * delete方法
	 * 
	 * @param url
	 * @param requestHeaders
	 * @return
	 */
	public static String httpDelete(String url, HashMap<String, String> requestHeaders) {

		HttpDelete httpdelete = new HttpDelete();

		try {
			httpdelete.setURI(new URI(url));

			for (Entry<String, String> entry : requestHeaders.entrySet()) {
				httpdelete.setHeader(entry.getKey(), entry.getValue());
			}
			response = httpClient.execute(httpdelete);

			// 如果server端返回http 200
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				HttpEntity responseEntity = response.getEntity();
				return EntityUtils.toString(responseEntity, "UTF-8");
			} else {
				String code = String.valueOf(response.getStatusLine().getStatusCode());
				
				return "请求失败:" + code;
			}
		} catch (Exception e) {
			return "不可能出现";
		}
	}

}
